import 'package:lz_app_core/kd_user/kd_user_info.dart';
import 'package:lz_app_core/utils/kd_storage.dart';
import 'package:lz_ctcenter/kd_ctcenter.dart';

import '../serve/kd_login_api.dart';
import '../serve/models/kd_mine_info_detail_model.dart';

class KDUserMixinPlugin with CTUserMixin {
  @override
  Future<bool> reLogin() async {
    var phone = KDStorage.get<String>(KDStorageKey.phone.name) ?? '';
    var pwd = KDStorage.get<String>(KDStorageKey.pwd.name) ?? '';
    return KDLoginApi.login(phone: phone, pwd: pwd);
  }

  @override
  Future<bool> updateMemberInfo() async {
    KDInfoDetailModel? infoModel = await KDLoginApi.mineDetailInfo();
    if (infoModel != null) {
      List<KDUserMainOrgAndMemberVOS>? datas =
          KDUser.info.userMainOrgAndMemberVOS;
      if (datas != null && datas.isNotEmpty) {
        for (var element in datas) {
          if (infoModel.memberId != null) {
            element.memberId = infoModel.memberId;
          }
          if (infoModel.memberCertificationNumber != null) {
            element.memberCertificationNumber =
                infoModel.memberCertificationNumber;
          }
        }
      } else {
        datas = [
          KDUserMainOrgAndMemberVOS()
            ..memberId = infoModel.memberId
            ..memberCertificationNumber = infoModel.memberCertificationNumber
        ];
      }

      // 保存组织机构的id
      if (infoModel.mainOrgId != null) {
        KDUser.info.currentMainOrgId = infoModel.mainOrgId;
      }

      KDUser.save(userJson: KDUser.info.toJson(), userInfo: KDUser.info);
      return true;
    } else {
      return false;
    }
  }
}
